
// 添加一个标记,避免多个请求同时刷新token
import { RequestQueue } from '@/utils/RequestQueue.ts'
import { useUserStore } from '@/stores/user.ts'
import { fetch } from '@tauri-apps/plugin-http'
import urls from '@/services/urls.ts'

let isRefreshing = false
// 使用队列实现
const requestQueue = new RequestQueue()
export async function refreshTokenAndRetry(): Promise<string> {
  if (isRefreshing) {
    console.log('🔄 已有刷新请求在进行中，加入等待队列')
    return new Promise((resolve) => {
      // 可以根据请求类型设置优先级
      requestQueue.enqueue(resolve, 1)
    })
  }

  isRefreshing = true
  try {
    const refreshToken = localStorage.getItem('REFRESH_TOKEN')
    if (!refreshToken) {
      console.error('❌ 无刷新令牌')
      throw new Error('无刷新令牌')
    }

    const userStore = useUserStore()
    const token = localStorage.getItem('TOKEN')

    const httpHeaders = new Headers({})
    // httpHeaders.set('Content-Type', 'multipart/form-data')
    httpHeaders.set('Authorization', `Bearer ${token}`)

    const formData = new FormData()
    formData.append('refreshToken', refreshToken)
    formData.append('userId', userStore.userInfo?.UserId as string)
    const httpParams: RequestInit = {
      method: 'POST',
      headers: httpHeaders,
      body: formData
    }
    console.log('📤 正在使用refreshToken获取新的token', refreshToken)

    const response = await fetch(urls.refreshToken, httpParams)

    const data = await response.json()

    if (!response.ok || !data.successful) {
      // 重新登录
      window.dispatchEvent(new Event('needReLogin'))
      throw new Error('刷新令牌失败')
    }
    const { Token, RefreshToken: newRefreshToken } = data.data

    console.log('🔑 Token刷新成功，更新存储', data)
    // 更新本地存储的token 知道
    localStorage.setItem('TOKEN', Token)
    localStorage.setItem('REFRESH_TOKEN', newRefreshToken)
    userStore.userInfo = data.data

    // 使用队列处理方式
    await requestQueue.processQueue(Token)

    return Token
  } catch (error) {
    console.error('❌ 刷新Token过程出错:', error)
    requestQueue.clear() // 发生错误时清空队列
    window.dispatchEvent(new Event('needReLogin'))
    throw error
  } finally {
    isRefreshing = false
  }
}
